<template>
  <div v-chart-resize ref="chartRef" class="echarts" :style="{ width: width, height: height }"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from "vue";
import * as echarts from "echarts";
const emit = defineEmits(["echartClick"]);
const props = defineProps({
  // 配置项
  options: {
    type: Object,
    required: true,
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "400px",
  },
});

const chartRef = ref(null);
let chartInstance = null;

// 初始化图表
const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
     if(!props.options){
      console.error("options is null");
      return
    }
    
    chartInstance.setOption(props.options);
    // 柱状体点击事件
    chartInstance.on("click", (params) => {
      emit("echartClick", params);
    });
  }
};

// 更新图表
const updateChart = () => {
  if (chartInstance) {
    chartInstance.clear();
    chartInstance.setOption(props.options);
  }
};

// 监听窗口大小变化，自适应图表
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 组件挂载时初始化图表
onMounted(() => {
  initChart();
  window.addEventListener("resize", resizeChart);
});

// 组件卸载时销毁图表
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener("resize", resizeChart);
});

watch(
  () => props.options,
  () => {
    updateChart();
  },
  { deep: true }
);
</script>
